package com.otitan.la.forest.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.otitan.la.forest.system.dto.PermissionRoleDTO;
import com.otitan.la.forest.system.entity.PermissionRoleEntity;
import com.otitan.la.forest.system.mapper.PermissionRoleMapper;
import com.otitan.la.forest.system.service.PermissionRoleService;
import com.otitan.webapp.framework.basepro.exception.code.BaseResponseCode;
import com.otitan.webapp.framework.basepro.model.DataResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;

@Slf4j
@Service
public class PermissionRoleServiceImpl extends ServiceImpl<PermissionRoleMapper, PermissionRoleEntity> implements PermissionRoleService {

    @Transactional
    @Override
    public DataResult add(PermissionRoleDTO permissionRoleDTO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return DataResult.fail(bindingResult.getFieldError().getDefaultMessage());
        }
         PermissionRoleEntity permissionRoleEntity = new PermissionRoleEntity();
        permissionRoleEntity.setRoleId(permissionRoleDTO.getRoleId());
        permissionRoleEntity.setPermissionId(permissionRoleDTO.getPermissionId());
        // 删除已存在的关联关系，防止主键冲突异常
        boolean isRemove=removeMenuAndRoleId(permissionRoleDTO);
        boolean isSuccess;
        if(permissionRoleDTO.getIsOpen().equals("yes")){
            isSuccess = this.save(permissionRoleEntity);
            return isSuccess ? DataResult.success() : DataResult.fail(BaseResponseCode.DATA_NOT_EXIST.getMsg());
        }
        return isRemove ? DataResult.success() : DataResult.fail(BaseResponseCode.DATA_NOT_EXIST.getMsg());
    }

    /**
     * 删除已存在的关联关系，防止主键冲突异常
     * @author Sunke
     * @param  permissionRoleDTO
     * @return boolean
     * @exception
     * @date 2020/9/24 0024 15:37
     */
    private boolean removeMenuAndRoleId(PermissionRoleDTO permissionRoleDTO) {
        LambdaQueryWrapper<PermissionRoleEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PermissionRoleEntity::getRoleId, permissionRoleDTO.getRoleId())
                .eq(PermissionRoleEntity::getPermissionId, permissionRoleDTO.getPermissionId());
        return this.remove(queryWrapper);
    }

}